package io.github.lee.jel.ui.detail

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.appcompat.widget.Toolbar
import androidx.core.os.bundleOf
import androidx.databinding.ViewDataBinding
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.core.ui.BaseActivity
import io.github.lee.core.ui.ba.gone
import io.github.lee.core.ui.databinding.ToolbarSimpleCenterTitleBinding
import io.github.lee.core.util.getBundleParcelable
import io.github.lee.core.util.isScreenLand
import io.github.lee.core.util.screenWidth
import io.github.lee.core.util.toDp
import io.github.lee.core.util.toPx
import io.github.lee.core.vm.err.DataParseFailedException
import io.github.lee.jel.R
import io.github.lee.jel.databinding.ActivityItemDetailBinding
import io.github.lee.jel.databinding.LayoutDefaultErrorBinding
import io.github.lee.jel.databinding.LayoutDefaultLoadingBinding
import io.github.lee.jel.databinding.LayoutPeopleAvatarBinding
import io.github.lee.jel.global.theme.ThemeManager
import io.github.lee.repository.jel.data.session
import io.github.lee.repository.jel.domain.Item
import io.github.lee.repository.jel.domain.People
import java.io.File

@AndroidEntryPoint
class ItemDetailActivity : BaseActivity<ActivityItemDetailBinding, ItemDetailVM>() {
    companion object {
        private const val KEY_ITEM = "ITEM"

        @JvmStatic
        fun start(context: Context, item: Item) {
            val starter = Intent(context, ItemDetailActivity::class.java)
                .putExtras(
                    bundleOf(
                        KEY_ITEM to item
                    )
                )
            context.startActivity(starter)
        }
    }

    //===Desc:=============================================================

    override fun onCreateViewModel(): Lazy<ItemDetailVM> =
        viewModels()

    override fun onCreateToolbar(): Toolbar =
        ToolbarSimpleCenterTitleBinding.inflate(layoutInflater)
            .also {
                if (isScreenLand(mContext)) {
                    it.bg = ThemeManager.toolbarColor(mContext)
                    it.title = getBundleParcelable(KEY_ITEM, Item::class.java)?.name
                } else {
                    it.bg = Color.TRANSPARENT
                    it.title = ""
                }
            }.toolbar

    override fun onCreateLoading(): ViewDataBinding =
        LayoutDefaultLoadingBinding.inflate(layoutInflater)

    override fun onCreateSuccess(): ActivityItemDetailBinding =
        ActivityItemDetailBinding.inflate(layoutInflater)

    override fun onCreateError(): ViewDataBinding =
        LayoutDefaultErrorBinding.inflate(layoutInflater)


    //===Desc:=============================================================

    override fun onInitData(savedInstanceState: Bundle?) {
        super.onInitData(savedInstanceState)
        isHover = !isScreenLand(mContext)
    }

    override fun onObserved() {
        super.onObserved()
        vm?.detailLiveData?.observe(this) {
            if (null == it) {
                showError(DataParseFailedException(mContext))
                return@observe
            }
            vb?.host = mContext.session?.host
            vb?.item = it
            peopleAvatar(it.people)
            val fileName = File(it.path ?: "").name
            val sessionName = mContext.session?.name
            if (!fileName.isNullOrEmpty()
                && !sessionName.isNullOrEmpty()
            ) {
                vb?.locationText = getString(R.string.txt_file_location, fileName, sessionName)
            }
        }
    }

    override fun onSetViewData() {
        super.onSetViewData()
        if (isScreenLand(mContext)) {
            statusBarColor(ThemeManager.statusBarColor(mContext), ThemeManager.isStatusBarDark())
        } else {
            statusBarColor(Color.TRANSPARENT, !ThemeManager.isStatusBarDark(), false)
        }
        navigationBarColor(ThemeManager.statusBarColor(mContext))

        val tint = if (isScreenLand(mContext)) {
            getColor(R.color.main_theme)
        } else {
            getColor(R.color.white)
        }
        setNavigationIcon(R.drawable.ic_arrow_back, tint) { finish() }

        vb?.llPeopleRoot?.removeAllViews()

        val item = getBundleParcelable(KEY_ITEM, Item::class.java)
        if (null == item) {
            showEmpty()
            return
        }
        vm?.itemDetail(item.id)
    }

    //====

    private fun peopleAvatar(list: List<People>?) {
        if (list.isNullOrEmpty()) {
            vb?.llPeopleContent?.gone(true)
            return
        }
        vb?.llPeopleContent?.gone(false)
        vb?.llPeopleRoot?.removeAllViews()
        list.forEachIndexed { index, people ->
            val peopleVB = LayoutPeopleAvatarBinding.inflate(layoutInflater)
            peopleVB.people = people

            val itemWidth = if (screenWidth(mContext).toDp(mContext) < 600) {
                screenWidth(mContext) / 6
            } else if (screenWidth(mContext).toDp(mContext) in 600..839
            ) {
                screenWidth(mContext) / 8
            } else {
                screenWidth(mContext) / 12
            }
            val params = LinearLayout.LayoutParams(
                itemWidth,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            when (index) {
                0 -> params.marginStart = 16.toPx(mContext)
                list.size - 1 -> {
                    params.marginStart = 8.toPx(mContext)
                    params.marginEnd = 16.toPx(mContext)
                }

                else -> params.marginStart = 8.toPx(mContext)
            }
            vb?.llPeopleRoot?.addView(peopleVB.root, params)
        }

    }

}

